﻿#include "CGameEngine.h"

//初始化引擎
bool CGameEngine::InitEngine(HINSTANCE hInstance, HWND hParent, DLGPROC proc)
{
	return this->m_Win.Create(hInstance, IDD_ENGINE_MAIN, hParent, proc);
}

//加载插件模块
void CGameEngine::LoadLibs()
{
	vector<TString> vtLibs;
	EnumLibs(vtLibs);

	typedef CEditor *(*pEditor)();	//定义函数指针类型，用于获取接口类指针
	for (int i = 0; i != vtLibs.size(); i++)
	{
		//加载库
		HINSTANCE hDll = LoadLibrary(vtLibs[i].c_str());
		if (hDll == NULL)
		{
			debug.TraceW(_T("加载模块 [%s] 失败...\n"), vtLibs[i].c_str());
		}

		//获取接口类指针
		pEditor pFun;
		pFun = (pEditor)GetProcAddress(hDll, "GetObj");
		CEditor *p = pFun();

		//把模块信息储存到列表中
		DLL_INFO dllinfo;
		dllinfo.hInstance = hDll;
		dllinfo.pEditor = p;

		//把模块信息加入队列
		this->m_vtDllList.push_back(dllinfo);

		p->AttachModule(hDll, this->m_Win.GetHandle(), m_vtDllList);
	}

}

//执行编辑器菜单处理函数
void CGameEngine::MenuCommand(UINT uId)
{
	//遍历调用DLL的OnMenuCommand菜单处理函数
	for (int i = 0; i != this->m_vtDllList.size(); i++)
	{
		m_vtDllList[i].pEditor->OnMenuCommand(uId);
	}
}

//遍历模块
void CGameEngine::EnumLibs(vector<TString> &vtLibraries)
{

	WIN32_FIND_DATA finder;
	HANDLE hFind = FindFirstFile(_T("lib\\*.dll"), &finder);

	if (hFind == INVALID_HANDLE_VALUE)
	{
		vtLibraries.clear();
		return;
	}
	else
	{
		do  
		{
			vtLibraries.push_back(finder.cFileName);
			debug.TraceW(_T("找到库 %s\n"), finder.cFileName);
		} while (FindNextFile(hFind, &finder));

		FindClose(hFind);
	}
}

//设置背景颜色
void CGameEngine::SetBkColor(COLORREF color)
{
	//设置窗口背景色
	PAINTSTRUCT ps; 
	HDC hdc; 
	HBRUSH brush, oldbrush;
	RECT rect;
	hdc = BeginPaint(this->m_Win.GetHandle(), &ps); 
	brush = CreateSolidBrush(color);//创建画刷
	GetClientRect(this->m_Win.GetHandle(), &rect);//获得主窗口的面积
	oldbrush =(HBRUSH)SelectObject(hdc, brush);
	Rectangle(hdc, rect.left, rect.top, rect.right, rect.bottom);
	SelectObject(hdc, oldbrush);  
	EndPaint(this->m_Win.GetHandle(), &ps);
}